package com.yxkj.railservicer.activity;

import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.yxkj.railservicer.R;
import com.yxkj.railservicer.application.MyApplication;
import com.yxkj.railservicer.util.ContentUtil;
import com.yxkj.railservicer.util.JSONUtil;
import com.yxkj.railservicer.util.SPUtil;
import com.yxkj.railservicer.util.ScreenUtils;
import com.yxkj.railservicer.util.SysApplicationUtil;

import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class TelLoginActivity extends AppCompatActivity implements View.OnClickListener {
    private static final String TAG = "TAG";

    private ImageView iv_main_back;
    private TextView tv_title;
    private ImageView iv_main_setting;
    private EditText et_tel_name;
    private EditText et_tel_auth;
    private Button btn_tel_auth;
    private Button btn_tel_login;

    private JSONUtil jsonUtil;
    private OkHttpClient client;

    private ProgressDialog dialog;

    private int countSeconds = 60;//倒计时秒数
    private Handler mCountHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (countSeconds > 0) {
                --countSeconds;
                btn_tel_auth.setText("(" + countSeconds + ")后获取验证码");
                mCountHandler.sendEmptyMessageDelayed(0, 1000);
            } else {
                countSeconds = 60;
                btn_tel_auth.setText("请重新获取验证码");
            }
        }
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_tel_login);
        ScreenUtils.setTranStatus(this, true, Color.parseColor("#2387f5"));
        SysApplicationUtil.getInstance().addActivity(this);
        initData();
        initEvent();

    }

    /**
     * 加载事件
     */
    private void initEvent() {
        iv_main_setting.setVisibility(View.INVISIBLE);
        tv_title.setText("登录");
        iv_main_back.setOnClickListener(this);
        btn_tel_auth.setOnClickListener(this);
        btn_tel_login.setOnClickListener(this);
    }

    /**
     * 加载数据
     */
    private void initData() {
        iv_main_back = (ImageView) findViewById(R.id.iv_main_back);
        tv_title = (TextView) findViewById(R.id.tv_title);
        iv_main_setting = (ImageView) findViewById(R.id.iv_main_setting);
        et_tel_name = (EditText) findViewById(R.id.et_tel_name);
        et_tel_auth = (EditText) findViewById(R.id.et_tel_auth);
        btn_tel_auth = (Button) findViewById(R.id.btn_tel_auth);
        btn_tel_login = (Button) findViewById(R.id.btn_tel_login);

        jsonUtil = new JSONUtil();
    }

    /**
     * 点击事件
     *
     * @param v
     */
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_main_back:
                finish();
                break;
            case R.id.btn_tel_auth:
                getAuth();
                break;
            case R.id.btn_tel_login:
                login();

                break;
        }
    }

    /**
     * 登录
     */
    private void login() {
        dialog = ProgressDialog.show(this, "提示", "正在登录，请稍后");
        String code = et_tel_auth.getText().toString();
        Log.e(TAG, "login: " + token);
        String message = "?phoneNo=" + phoneNo + "&code=" + code;
        client = new OkHttpClient();
        Request request = new Request.Builder()
                .addHeader("token", token)
                .url(ContentUtil.message_login_url + message)
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                toast("服务器繁忙，请稍后再试");
                dismiss();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String dataMessage = response.body().string();
                Log.e(TAG, "onResponse: " + dataMessage);
                if (jsonUtil.validate(dataMessage)) {

                    JSONObject jsonObject = JSON.parseObject(dataMessage);
                    Boolean success = jsonObject.getBoolean("success");
                    if (success) {
                        String name = jsonObject.getJSONObject("data").getString("name");
                        String phoneNo = jsonObject.getJSONObject("data").getString("phoneNo");
                        SPUtil.setString(TelLoginActivity.this, "name", name);
                        SPUtil.setString(TelLoginActivity.this, "phoneNo", phoneNo);
                        Intent intent = new Intent(TelLoginActivity.this, MainActivity.class);
                        startActivity(intent);
                        finish();
                    } else {
                        toast(jsonObject.getString("message"));
                    }
                }
                dismiss();
            }
        });

    }

    private String phoneNo;

    /**
     * 获取验证码
     */
    private void getAuth() {
        if (countSeconds == 60) {
            phoneNo = et_tel_name.getText().toString();
            Log.e("tag", "phoneNo==" + phoneNo);
            getMobiile(phoneNo);
        } else {
            toast("不能重复发送验证码");
        }

    }

    //使用正则表达式判断电话号码
    public static boolean isphoneNoNO(String tel) {
        Pattern p = Pattern.compile("^(13[0-9]|15([0-3]|[5-9])|14[5,7,9]|17[1,3,5,6,7,8]|18[0-9])\\d{8}$");
        Matcher m = p.matcher(tel);
        System.out.println(m.matches() + "---");
        return m.matches();
    }

    //获取验证码信息,进行计时操作
    private void startCountBack() {
        (this).runOnUiThread(new Runnable() {
            @Override
            public void run() {
                btn_tel_auth.setText(countSeconds + "");
                mCountHandler.sendEmptyMessage(0);
            }
        });
    }

    //随机生成验证码
    private String getNotes() {

        double i = Math.random() * 9000 + 1000;
        int j = (int) i;
        return j + "";
    }

    //获取验证码信息，判断是否有手机号码
    private void getMobiile(String phoneNo) {
        if ("".equals(phoneNo)) {
            Log.e("tag", "phoneNo=" + phoneNo);
            new AlertDialog.Builder(this).setTitle("提示").setMessage("手机号码不能为空").setCancelable(true).show();
        } else if (!isphoneNoNO(phoneNo)) {
            new AlertDialog.Builder(this).setTitle("提示").setMessage("请输入正确的手机号码").setCancelable(true).show();
        } else {
            Log.e("tag", "输入了正确的手机号");
            requestVerifyCode(phoneNo);
        }
    }

    private String code;
    private String token;

    //获取验证码信息，进行验证码请求
    private void requestVerifyCode(String phoneNo) {
        dialog = ProgressDialog.show(this, "提示", "正在获取验证码，请稍后");
        String message = "?phoneNo=" + phoneNo;
        client = new OkHttpClient();
        Request request = new Request.Builder()
                .url(ContentUtil.message_url + message)
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                toast("服务器繁忙，请稍后再试");
                dismiss();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                startCountBack();
                String dataMessage = response.body().string();
                if (jsonUtil.validate(dataMessage)) {
                    Log.e("TAG", dataMessage);
                    JSONObject jsonObject = JSON.parseObject(dataMessage);
                    Boolean success = jsonObject.getBoolean("success");
                    if (success) {
                        token = jsonObject.getJSONObject("data").getString("token");
                        SPUtil.setString(TelLoginActivity.this, "token", token);

                    } else {
                        toast(jsonObject.getString("message"));
                    }
                }
                dismiss();
            }
        });
    }

    private void toast(final String string) {
        this.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(TelLoginActivity.this, string, Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void dismiss() {
        this.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                dialog.dismiss();
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        SysApplicationUtil.getInstance().deleteActivity(this);
    }
}
